﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace XyLicense.Library
{
    /// <summary>
    /// RSA加密
    /// </summary>
    public class RSAHelper
    {

        public static string Encrypto(string source, string m_PubKey)
        {
            return getEncryptoInfoByRSA(source, m_PubKey);
        }

        public static string Decrypto(string dest, string m_PriKey)
        {
            return getDecryptoInfoByRSA(dest, m_PriKey);
        }

        private static string getEncryptoInfoByRSA(string source, string m_PubKey)
        {
            byte[] plainByte = Encoding.ASCII.GetBytes(source);
            //初始化参数
            RSACryptoServiceProvider asym = new RSACryptoServiceProvider();
            asym.FromXmlString(m_PubKey);
            int keySize = asym.KeySize / 8;//非对称加密，每次的长度不能太长，否则会报异常
            int bufferSize = keySize - 11;
            if (plainByte.Length > bufferSize)
            {
                throw new Exception("非对称加密最多支持【" + bufferSize + "】字节，实际长度【" + plainByte.Length + "】字节。");
            }
            byte[] cryptoByte = asym.Encrypt(plainByte, false);
            return Convert.ToBase64String(cryptoByte);
        }

        private static string getDecryptoInfoByRSA(string dest, string m_PriKey)
        {
            byte[] btDest = Convert.FromBase64String(dest);
            //初始化参数
            RSACryptoServiceProvider asym = new RSACryptoServiceProvider();
            asym.FromXmlString(m_PriKey);
            int keySize = asym.KeySize / 8;//非对称加密，每次的长度不能太长，否则会报异常
                                           //int bufferSize = keySize - 11;
            if (btDest.Length > keySize)
            {
                throw new Exception("非对称解密最多支持【" + keySize + "】字节，实际长度【" + btDest.Length + "】字节。");
            }
            byte[] cryptoByte = asym.Decrypt(btDest, false);
            return Encoding.ASCII.GetString(cryptoByte);
        }


    }
}
